/**************************************************************
 *   File:	Renderer.cpp
 * Author:	Andrew Thorpe
 *  Brief:	A system to render ScreenQuads
 **************************************************************/
#include "StdAfx.h"
#include "Renderer.h"
#include "ScreenQuad.h"

using namespace Fossil;
static const int MAX_NESTED_DEPTH = 100;

void Renderer::Initialise()
{
	m_pRenderStages = new RenderStage[MAX_NESTED_DEPTH];

	glShadeModel(GL_SMOOTH);
	glClearColor(1.0f, 0.0f, 0.0f, 1.0f);
	glClearDepth(1.0f);
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
}

void Renderer::Render(ScreenQuad* pScreenQuad)
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glLoadIdentity();

	m_pCurrentStage = 0;
	m_pRenderStages[0].width = m_Width;
	m_pRenderStages[0].height = m_Height;
	
	pScreenQuad->Render(m_Width, m_Height, -1.0f);
	RenderChildren(pScreenQuad);
}

void Renderer::RenderChildren(ScreenQuad* pScreenQuad)
{
	ScreenQuad* current = pScreenQuad->Child();

	++m_pCurrentStage;
	float w = m_pRenderStages[m_pCurrentStage].width * pScreenQuad->m_Width;
	float h = m_pRenderStages[m_pCurrentStage].height * pScreenQuad->m_Height;

	while(current)
	{
		current->Render(w, h, (float)-m_pCurrentStage);
		current = current->Next();
	}
	--m_pCurrentStage;
}

void Renderer::Resize(int width, int height)
{
	if (height == 0)
	{
		height = 1;
	}

	m_Width = (float)width;
	m_Height = (float)height;

	glViewport(0, 0, width, height);
	glScissor(0, 0, width, height);

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();

	glOrtho(0.0f, width, 0.0f, height, 0.1f, 1000.0f);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
}

void Renderer::Destroy()
{
	Singleton::Destroy();
}
